package com.qqim.client;

import com.qqim.client.cache.CacheManager;
import com.qqim.client.network.NetworkManager;
import com.qqim.client.ui.LoginDialog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.nio.charset.Charset;
import java.util.Locale;

/**
 * 客户端主程序
 */
public class ClientMain {
    private static final Logger logger = LoggerFactory.getLogger(ClientMain.class);
    
    private NetworkManager networkManager;
    private CacheManager cacheManager;
    
    // 静态块，在类加载时就设置编码
    static {
        try {
            // === 第一层：JVM系统属性设置 ===
            System.setProperty("file.encoding", "UTF-8");
            System.setProperty("sun.jnu.encoding", "UTF-8");
            System.setProperty("native.encoding", "UTF-8");
            System.setProperty("console.encoding", "UTF-8");
            System.setProperty("java.nio.charset.Charset.defaultCharset", "UTF-8");
            
            // === 第二层：强制反射设置默认字符集 ===
            try {
                java.lang.reflect.Field charset = Charset.class.getDeclaredField("defaultCharset");
                charset.setAccessible(true);
                charset.set(null, null);  // 重置缓存，强制重新读取系统属性
                
                // 验证设置
                Charset defaultCharset = Charset.defaultCharset();
                if (!"UTF-8".equals(defaultCharset.name())) {
                    System.err.println("警告：默认字符集不是UTF-8，当前为: " + defaultCharset.name());
                }
            } catch (Exception e) {
                System.err.println("反射设置字符集失败: " + e.getMessage());
            }
            
            // === 第三层：本地化和语言设置 ===
            Locale.setDefault(Locale.SIMPLIFIED_CHINESE);
            System.setProperty("user.language", "zh");
            System.setProperty("user.country", "CN");
            System.setProperty("user.variant", "");
            
            // === 第四层：Swing相关编码设置 ===
            System.setProperty("swing.defaultlaf", UIManager.getSystemLookAndFeelClassName());
            System.setProperty("awt.useSystemAAFontSettings", "on");
            System.setProperty("swing.aatext", "true");
            
            // === 调试信息输出 ===
            System.out.println("=== 字符编码设置完成 ===");
            System.out.println("默认字符集: " + Charset.defaultCharset().name());
            System.out.println("文件编码: " + System.getProperty("file.encoding"));
            System.out.println("JNU编码: " + System.getProperty("sun.jnu.encoding"));
            System.out.println("本地化: " + Locale.getDefault());
            System.out.println("系统语言: " + System.getProperty("user.language"));
            System.out.println("=========================");
            
        } catch (Exception e) {
            System.err.println("设置编码失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        // 设置渲染相关属性
        System.setProperty("awt.useSystemAAFontSettings", "on");
        System.setProperty("swing.aatext", "true");
        System.setProperty("swing.defaultlaf", UIManager.getSystemLookAndFeelClassName());
        
        // 设置字体渲染质量
        System.setProperty("swing.plaf.metal.controlFont", "Microsoft YaHei");
        System.setProperty("swing.plaf.metal.systemFont", "Microsoft YaHei");
        System.setProperty("swing.plaf.metal.userFont", "Microsoft YaHei");
        System.setProperty("swing.plaf.metal.smallFont", "Microsoft YaHei");
        
        SwingUtilities.invokeLater(() -> {
            try {
                // 设置Look and Feel
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                
                // 设置字体
                initializeFonts();
                
                new ClientMain().start();
            } catch (Exception e) {
                logger.error("启动失败", e);
                System.err.println("启动失败: " + e.getMessage());
            }
        });
    }
    
    private static void initializeFonts() {
        // 尝试多种字体，确保中文能正确显示
        String[] fontNames = {
            "Microsoft YaHei UI", "Microsoft YaHei", "SimSun", "宋体", "黑体", "微软雅黑",
            "Noto Sans CJK SC", "Source Han Sans CN", "PingFang SC", "Hiragino Sans GB"
        };
        
        Font defaultFont = null;
        
        // 找到可用的字体
        for (String fontName : fontNames) {
            try {
                Font testFont = new Font(fontName, Font.PLAIN, 12);
                if (testFont.canDisplay('中') && testFont.canDisplay('文')) {
                    defaultFont = testFont;
                    System.out.println("使用字体: " + fontName);
                    break;
                }
            } catch (Exception e) {
                // 忽略异常，继续尝试下一个字体
            }
        }
        
        // 如果没有找到合适的字体，使用系统默认字体
        if (defaultFont == null) {
            defaultFont = new Font(Font.DIALOG, Font.PLAIN, 12);
            System.out.println("使用系统默认字体: " + defaultFont.getName());
        }
        
        // 设置所有UI组件的字体
        Font boldFont = defaultFont.deriveFont(Font.BOLD);
        Font largeFont = defaultFont.deriveFont(16f);
        
        UIManager.put("Label.font", defaultFont);
        UIManager.put("Button.font", defaultFont);
        UIManager.put("TextField.font", defaultFont);
        UIManager.put("TextArea.font", defaultFont);
        UIManager.put("List.font", defaultFont);
        UIManager.put("ComboBox.font", defaultFont);
        UIManager.put("Table.font", defaultFont);
        UIManager.put("Tree.font", defaultFont);
        UIManager.put("Menu.font", defaultFont);
        UIManager.put("MenuItem.font", defaultFont);
        UIManager.put("CheckBox.font", defaultFont);
        UIManager.put("RadioButton.font", defaultFont);
        UIManager.put("TabbedPane.font", defaultFont);
        UIManager.put("TitledBorder.font", defaultFont);
        UIManager.put("OptionPane.font", defaultFont);
        UIManager.put("Panel.font", defaultFont);
        
        // 设置窗口标题栏字体
        UIManager.put("InternalFrame.titleFont", boldFont);
        
        System.out.println("字体初始化完成");
    }
    
    private void start() {
        logger.info("QQ即时通信客户端启动");
        
        networkManager = new NetworkManager();
        cacheManager = new CacheManager();
        
        // 显示登录对话框
        new LoginDialog(this).setVisible(true);
    }
    
    public NetworkManager getNetworkManager() {
        return networkManager;
    }
    
    public CacheManager getCacheManager() {
        return cacheManager;
    }
}
 